
import userApi from "@/request/api/userApi.js"
import globalWebsocket from "@/request/websocket/GlobalWebsocket.js"
const userCookieKey = "user"  //存储用户信息的cookie key
const userTokenKey = "token"  //存储用户token的 key

export default {
	//获取当前已登录用户的id
	getLoginUserId() {
		let token = uni.getStorageSync("token");
		if(token == null || token =='') return null;
		let base64Url = token.split('.')[1];
		let base64 = base64Url.replace('-', '+').replace('_', '/');
		let tonkenInfo = JSON.parse(window.atob(base64));
		return tonkenInfo.sub;
	},
	
	//登录检查
	loginCheck(){
		let loginUser = uni.getStorageSync(userCookieKey)
		return new Promise((resolve,reject)=>{
			if(loginUser){
				//如果登陆了 返回成功
				resolve(loginUser)
			}else{
				//提示用户是否登录
				uni.showModal({
					title: '提示',
					content: '当前操作需要登录,是否前往?',
					success: function (res) {
						//如果用户点击了确定 跳转到登录页面
						if (res.confirm) {

							uni.navigateTo({
								url: '/pages/login/login'
							});
						}else if(res.cancel){
							//如果用户点了取消 返回失败
							reject("用户取消了登录")
						}
					},
				});
			}
		})	
	},
	//获取登录用户的信息
	getLoginUserInfo(){
		return uni.getStorageSync(userCookieKey);
	},
	//设置登录用户的信息存到cookie中
	setLoginUserInfo(userInfo){
		return uni.setStorageSync(userCookieKey,userInfo);
	},
	logout(){
		uni.removeStorageSync(userTokenKey);
		uni.removeStorageSync(userCookieKey);
		globalWebsocket.close()//退出登录，关闭全局通知socket
	},
	getToken(){
		return uni.getStorageSync(userTokenKey);
	},
	//登录成功后，保存登录相关的信息
	async saveLoginInfo(token){
		uni.setStorageSync(userTokenKey,token); //存入缓存
		let userData = await userApi.userBaseInfo(this.getLoginUserId());
		if(userData.code == 0){
			uni.setStorageSync('user',userData.user); //用户信息存入缓存
		}
		globalWebsocket.open()//登录成功打开全局通知socket
	}
}

